package cn.itcast.mobilebrowser.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;

import java.util.ArrayList;
import java.util.List;

import cn.itcast.mobilebrowser.R;
import cn.itcast.mobilebrowser.adapter.WebTabListAdapter;
import cn.itcast.mobilebrowser.model.WebTab;
import cn.itcast.mobilebrowser.viewmodel.WebTabViewModel;

/**
 * 标签管理页的Fragment
 */
public class WebTabFragment extends Fragment {

    private final String TAG = "WebTabFragment";

    private WebTabViewModel mViewModel;
    private WebTabListAdapter listAdapter;

    private Button addButton;
    private Button closeButton;
    private RecyclerView recyclerView;

    public static WebTabFragment newInstance() {
        return new WebTabFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mViewModel = new ViewModelProvider(requireActivity()).get(WebTabViewModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_web_tab, container, false);

        closeButton = view.findViewById(R.id.close_fragment_button);
        addButton = view.findViewById(R.id.add_tab_button);
        recyclerView = view.findViewById(R.id.tab_list_view);

        this.initView();
        // 设置测试数据
        // this.initData();

        // 观察当前列表，有改动就提交给ListAdapter
        mViewModel.getMutableLiveData().observe(getViewLifecycleOwner(), new Observer<List<WebTab>>() {
            @Override
            public void onChanged(List<WebTab> webTabs) {
                Log.d(TAG, "" + webTabs.size());
                listAdapter.submitList(new ArrayList<>(webTabs));
                // listAdapter.notifyDataSetChanged();
            }
        });

        return view;
    }

    private void initView() {
        // 返回按钮被按下
        closeButton.setOnClickListener(v -> {
            requireActivity().getSupportFragmentManager().beginTransaction()
                    .setCustomAnimations(R.anim.popup_in, R.anim.popup_out)
                    .remove(this)
                    .commit();
        });

        // 添加一个新标签
        addButton.setOnClickListener(v -> {
            // 获取标签页总数
            int itemCount = WebTab.NUM;
            // 测试的bitmap
            // Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test_tab_image);
            // 生成新的web view
            WebView webView = new WebView(requireActivity());
            webView.loadUrl("https://www.bilibili.com");
            webView.setDrawingCacheEnabled(true);
            WebTab webTab = new WebTab("webView" + (itemCount+1),
                    webView.getDrawingCache(), webView);
            // 插入列表
            mViewModel.addTab(webTab);
            mViewModel.setCurrentTab(webTab);
            closeButton.callOnClick();
        });

        // 设置增删动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        // 设置适配器，传入点击事件
        listAdapter = new WebTabListAdapter(new WebTabListAdapter.OnTabClickListener() {
            @Override
            public void onTabClick(View view, int position) {
                // 打开这个web view
                List<WebTab> list = listAdapter.getCurrentList();
                Log.d(TAG, list.get(position).getTitle());
                mViewModel.setCurrentTab(list.get(position));
                // 打开后关闭当前fragment
                closeButton.callOnClick();
            }

            @Override
            public void onTabCloseClick(View view, int position) {
                WebTab current = mViewModel.getCurrentTab().getValue();
                List<WebTab> tabList = listAdapter.getCurrentList();

                // 只剩下一个tab时，删完要加一个
                if (tabList.size() <= 1) {
                    mViewModel.deleteTab(position);
                    addButton.callOnClick();
                } else {
                    // 不止一个tab时，删完可能需要切换tab
                    // 若当前显示的tab就是要被删的，需要先更改当前tab
                    if (current == tabList.get(position)) {
                        // 若有下一个就取下一个，没有就取上一个
                        // 取上一个时得判断是否越界，即list长度至少得大于1
                        // 如果只剩一个被删了的话，add button会处理
                        if (position < tabList.size() - 1) {
                            mViewModel.setCurrentTab(tabList.get(position + 1));
                        } else {
                            mViewModel.setCurrentTab(tabList.get(position - 1));
                        }
                    }
                    mViewModel.deleteTab(position);
                }

            }
        });
        recyclerView.setAdapter(listAdapter);
    }

    private void initData() {
        List<WebTab> list = new ArrayList<>();
        // 打开三个网页
        WebView webView1 = new WebView(requireActivity());
        webView1.loadUrl("https://www.bilibili.com");
        webView1.setDrawingCacheEnabled(true);
        WebTab webTab1 = new WebTab(webView1.getTitle(), webView1.getDrawingCache(), webView1);

        WebView webView2 = new WebView(requireActivity());
        webView2.loadUrl("https://www.bing.com");
        webView2.setDrawingCacheEnabled(true);
        WebTab webTab2 = new WebTab(webView2.getTitle(), webView2.getDrawingCache(), webView2);

        WebView webView3 = new WebView(requireActivity());
        webView3.loadUrl("https://www.zhihu.com");
        webView3.setDrawingCacheEnabled(true);
        WebTab webTab3 = new WebTab(webView3.getTitle(), webView3.getDrawingCache(), webView3);

        Log.d(TAG, webView1.getTitle());

        list.add(webTab1);
        list.add(webTab2);
        list.add(webTab3);

        listAdapter.submitList(list);
    }


}